package com.wythe.mall.ui;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wythe.mall.R;
import com.wythe.mall.activity.BuyActivity;
import com.wythe.mall.activity.LoginActivity;
import com.wythe.mall.activity.MainActivity;
import com.wythe.mall.adapter.MyFragmentPagerAdapter;
import com.wythe.mall.adapter.SpecListAdapter;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.CarBean;
import com.wythe.mall.model.SizeBean;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.Constants;
import com.wythe.mall.utils.DPIUtil;
import com.wythe.mall.utils.DensityUtils;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.ToastUtil;
import com.wythe.mall.utils.UserManager;
import com.wythe.mall.view.CenterTextView;
import com.wythe.mall.view.ScrollByViewpager;
import com.wythe.mall.view.dialog.GoodSizePopupwindow;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GoodsFragment extends Fragment implements GoodSizePopupwindow.OnSelectTextListener, View.OnClickListener {

    private Banner mainBanner;
    private AppCompatTextView nameTextView;
    private AppCompatTextView descTextView;
    private AppCompatTextView moneyTextView;
    private AppCompatTextView marketPriceTextView;
    private AppCompatImageView manSongGoodsImageView;
    private RelativeLayout specRelativeLayout;
    private AppCompatTextView specOneTextView;
    private CenterTextView customerTextView;
    private CenterTextView cartTextView;
    private AppCompatTextView addCartTextView;
    private AppCompatTextView buyTextView;
    private RelativeLayout chooseRelativeLayout;
    private AppCompatImageView chooseGoodsImageView;
    private AppCompatTextView chooseNameTextView;
    private AppCompatTextView chooseMoneyTextView;
    private AppCompatTextView chooseStorageTextView;
    private View chooseLineOneView;
    private View chooseLineTwoView;
    private AppCompatTextView chooseValueOneTextView;
    private AppCompatTextView chooseValueTwoTextView;
    private RecyclerView chooseValueOneRecyclerView;
    private RecyclerView chooseValueTwoRecyclerView;
    private View[] chooseLineView;
    private AppCompatTextView[] chooseValueTextView;
    private RecyclerView[] chooseValueRecyclerView;
    private AppCompatTextView chooseAddTextView;
    private AppCompatEditText chooseNumberEditText;
    private AppCompatTextView chooseSubTextView;
    private LinearLayoutCompat voucherLinearLayout;
    private TextView mSaleNum;
    private int currentPosition;

    private View view;

    private String goodsId;
    private String storeId;
    private String memberId;
    private String jsonString;
    private boolean haveGoods;
    private boolean isFavorites;
    private boolean isBackBoolean;
    private String manSongGoodsId;
    private String lowerLimitString;
    private String upperLimitString;
    private int goodsStorageString = 0;

    private String shareUrl;
    private String shareText;
    private String shareTitle;
    private String shareTitleUrl;
    private String shareImageUrl;
    private int mGoodsId;
    private List<String> mImgList;
    private List<SizeBean> mSizeList;
    private TextView addCartNumTv;

    private String[] specString;
    private SpecListAdapter specListAdapter;
    private GoodSizePopupwindow sizePopWin;
    private List<CarBean> mCarBeans;
    private String mShopName;
    private String mStoreName;
    private int flagShow;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private List<String> mTopTabTitle;
    private List<Fragment> mFragments;
    private int screenWidth;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        screenWidth = DensityUtils.screenWidth(getActivity());
        Bundle bundle = getArguments();
        if (bundle != null) {
            mGoodsId = bundle.getInt("id");
        }
        if (mImgList == null) {
            mImgList = new ArrayList<>();
        }
        mImgList.clear();
        if (mSizeList == null) {
            mSizeList = new ArrayList<>();
        }
        mSizeList.clear();
        if (mCarBeans == null) {
            mCarBeans = new ArrayList<>();
        }
        mCarBeans.clear();

        if (mTopTabTitle == null) {
            mTopTabTitle = new ArrayList<>();
        }
        mTopTabTitle.add("商品介绍");
        mTopTabTitle.add("商品评价");

        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {
        view = inflater.inflate(R.layout.fragment_goods_goods, viewGroup, false);
        initView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getGoodsInfo();
        initEven();
    }

    private void getGoodsInfo() {
        JSONObject param = new JSONObject();
        try {
            param.put("id", mGoodsId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiOkHttp.getGoodsInfo(getActivity(), param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                JSONObject jsonObject = null;
                JSONArray imgList = null;
                JSONArray skuVos = null;
                try {
                    jsonObject = data.getJSONObject("data");
                    int collect = jsonObject.getInt("collect");
                    if (collect == 1) {
                        customerTextView.setSelected(true);
                    } else {
                        customerTextView.setSelected(false);
                    }
                    imgList = jsonObject.getJSONArray("imgList");
                    skuVos = jsonObject.getJSONArray("skuVos");
                    mSaleNum.setText("销量：" + jsonObject.getString("totalSales") + "件");
                    mStoreName = jsonObject.getJSONObject("settlementVo").getString("title");
                    manSongGoodsId = jsonObject.getString("id");

                    for (int i = 0; i < imgList.length(); i++) {
                        String imgListString = imgList.getString(i);
                        mImgList.add(imgListString);
                    }
                    mainBanner.setImages(mImgList);
                    for (int i = 0; i < skuVos.length(); i++) {
                        SizeBean bean = new Gson().fromJson(skuVos.getJSONObject(i).toString(), SizeBean.class);
                        mSizeList.add(bean);
                    }

                    specListAdapter.notifyDataSetChanged();
                    goodsStorageString = mSizeList.get(0).getStockCount();
                    chooseValueTextView[0].setText("商品规格");
                    specOneTextView.setText(mSizeList.get(0).getTitle());
//                    webView.loadUrl("https://upload-images.jianshu.io/upload_images/1797490-012666441f452c00.png");
                    mShopName = jsonObject.getString("title");
                    nameTextView.setText(mShopName);
                    descTextView.setText(jsonObject.getString("represent"));
                    moneyTextView.setText("￥" + mSizeList.get(0).getPrice());
                    marketPriceTextView.setText("￥" + mSizeList.get(0).getOriginalPrice());
                    marketPriceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
//                    webView.loadUrl(jsonObject.getString("content"));
                    mFragments.add(DetailedFragment.getInstance(jsonObject.getString("content")));
                    mFragments.add(EvaluateFragment.getInstance(manSongGoodsId));

                    mViewPager.setAdapter(new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager(), mTopTabTitle, mFragments));
                    mTabLayout.setupWithViewPager(mViewPager);
                    mViewPager.setOffscreenPageLimit(2);
                    mViewPager.setCurrentItem(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    public void initView() {
        mainBanner = (Banner) view.findViewById(R.id.mainBanner);
        ViewGroup.LayoutParams layoutParams = mainBanner.getLayoutParams();
        layoutParams.height = screenWidth;
        mainBanner.setLayoutParams(layoutParams);
        mainBanner.setBannerStyle(Banner.CIRCLE_INDICATOR);
        mainBanner.setIndicatorGravity(Banner.CENTER);
        mainBanner.setDelayTime(5000);//设置轮播间隔时间
        mainBanner.isAutoPlay(true);
        mSaleNum = view.findViewById(R.id.tv_sale_num);
        mViewPager = view.findViewById(R.id.goods_viewpager);
        mTabLayout = view.findViewById(R.id.goods_tabLayout);

        chooseGoodsImageView = (AppCompatImageView) view.findViewById(R.id.chooseGoodsImageView);
        chooseNameTextView = (AppCompatTextView) view.findViewById(R.id.chooseNameTextView);
        chooseMoneyTextView = (AppCompatTextView) view.findViewById(R.id.chooseMoneyTextView);
        chooseStorageTextView = (AppCompatTextView) view.findViewById(R.id.chooseStorageTextView);
        chooseValueOneTextView = (AppCompatTextView) view.findViewById(R.id.chooseValueOneTextView);
        chooseValueOneRecyclerView = (RecyclerView) view.findViewById(R.id.chooseValueOneRecyclerView);
        chooseValueTwoTextView = (AppCompatTextView) view.findViewById(R.id.chooseValueTwoTextView);
        chooseValueTwoRecyclerView = (RecyclerView) view.findViewById(R.id.chooseValueTwoRecyclerView);


        nameTextView = (AppCompatTextView) view.findViewById(R.id.nameTextView);
        descTextView = (AppCompatTextView) view.findViewById(R.id.descTextView);
        moneyTextView = (AppCompatTextView) view.findViewById(R.id.moneyTextView);
        marketPriceTextView = (AppCompatTextView) view.findViewById(R.id.marketPriceTextView);
        manSongGoodsImageView = (AppCompatImageView) view.findViewById(R.id.manSongGoodsImageView);
        specRelativeLayout = (RelativeLayout) view.findViewById(R.id.specRelativeLayout);
        specOneTextView = (AppCompatTextView) view.findViewById(R.id.specOneTextView);

        customerTextView = (CenterTextView) view.findViewById(R.id.customerTextView);
        customerTextView.setOnClickListener(this);
        cartTextView = (CenterTextView) view.findViewById(R.id.cartTextView);

        addCartTextView = (AppCompatTextView) view.findViewById(R.id.addCartTextView);

        buyTextView = (AppCompatTextView) view.findViewById(R.id.buyTextView);

        chooseRelativeLayout = (RelativeLayout) view.findViewById(R.id.chooseRelativeLayout);

        chooseLineOneView = view.findViewById(R.id.chooseLineOneView);

        chooseLineTwoView = view.findViewById(R.id.chooseLineTwoView);

        chooseAddTextView = (AppCompatTextView) view.findViewById(R.id.chooseAddTextView);

        chooseNumberEditText = (AppCompatEditText) view.findViewById(R.id.chooseNumberEditText);

        chooseSubTextView = (AppCompatTextView) view.findViewById(R.id.chooseSubTextView);

        voucherLinearLayout = (LinearLayoutCompat) view.findViewById(R.id.voucherLinearLayout);

        specListAdapter = new SpecListAdapter(mSizeList);


        storeId = "";
        memberId = "";
        haveGoods = true;
        isFavorites = false;
        lowerLimitString = "";
        upperLimitString = "";
        specString = new String[]{"", ""};

        shareUrl = "";
        shareText = "";
        shareTitle = "";
        shareTitleUrl = "";
        shareImageUrl = "";

        chooseLineView = new View[2];
        chooseLineView[0] = chooseLineOneView;
        chooseLineView[1] = chooseLineTwoView;
        chooseValueTextView = new AppCompatTextView[2];
        chooseValueTextView[0] = chooseValueOneTextView;
        chooseValueTextView[1] = chooseValueTwoTextView;
        chooseValueRecyclerView = new RecyclerView[2];
        chooseValueRecyclerView[0] = chooseValueOneRecyclerView;
        chooseValueRecyclerView[1] = chooseValueTwoRecyclerView;
    }

    public void initEven() {

        cartTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putInt("skip", 111);
                GotoActivity.gotoActiviy(getActivity(), MainActivity.class, bundle);
                getActivity().finish();
            }
        });

        specRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showChooseLayout();
                flagShow = 3;
                showPopupwindow();
            }
        });
        chooseAddTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = (Integer.parseInt(chooseNumberEditText.getText().toString()) + 1) + "";
                chooseNumberEditText.setText(number);
                changeNumber();
            }
        });

        chooseNumberEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    changeNumber();
                }
                return false;
            }
        });

        chooseSubTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = (Integer.parseInt(chooseNumberEditText.getText().toString()) - 1) + "";
                chooseNumberEditText.setText(number);
                changeNumber();
            }
        });

        addCartTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManager.getInstance().isLogin()) {
                    GotoActivity.gotoActiviy(getActivity(), LoginActivity.class);
                    SharePreferenceUtils.removeString(getActivity(), "KEY_TOKEN");
                    return;
                }
                if (!haveGoods) {
                    Toast.makeText(getActivity(), "没货啦！", Toast.LENGTH_LONG).show();
                    return;
                }
//                if (chooseRelativeLayout.getVisibility() == View.GONE) {
//                    showChooseLayout();
                flagShow = 2;
                showPopupwindow();

//                } else {
//                    addCart();
//                }
            }
        });

        buyTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManager.getInstance().isLogin()) {
                    GotoActivity.gotoActiviy(getActivity(), LoginActivity.class);
                    SharePreferenceUtils.removeString(getActivity(), "KEY_TOKEN");
                    return;
                }
                if (!haveGoods) {
                    Toast.makeText(getActivity(), "没货啦！", Toast.LENGTH_LONG).show();
                    return;
                }
                if (chooseRelativeLayout.getVisibility() == View.GONE) {
//                    showChooseLayout();
                    flagShow = 1;
                    showPopupwindow();
                } else {
                    buy();
                }
            }
        });

    }

    @Override
    public void onStart() {
        super.onStart();
//        mainBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
//        mainBanner.stopAutoPlay();
        mainBanner.isAutoPlay(false);
    }

    @Override
    public void onSelectTextStatus(int position, String title) {
        currentPosition = position;
        specOneTextView.setText(title);
        goodsStorageString = mSizeList.get(position).getStockCount();
    }

    //自定义方法

    private void buy() {
        mCarBeans.clear();
        CarBean carBean = new CarBean();
        SizeBean sizeBean = mSizeList.get(currentPosition);
        carBean.setCount(Integer.valueOf((String) addCartNumTv.getText()));
        carBean.setIcon(sizeBean.getImg());
        carBean.setTitle(mShopName);
        carBean.setSkuId(sizeBean.getId());
        carBean.setSpecs(sizeBean.getTitle());
        carBean.setPrice(sizeBean.getPrice());
        carBean.setShop(mStoreName);
        mCarBeans.add(carBean);
        Integer integer = Integer.valueOf((String) addCartNumTv.getText());
        double totalMoney = sizeBean.getPrice() * Integer.valueOf((String) addCartNumTv.getText());

        Bundle bundle = new Bundle();
        bundle.putSerializable("list", (Serializable) mCarBeans);
        bundle.putDouble("money", totalMoney);
        bundle.putInt("count", Integer.valueOf((String) addCartNumTv.getText()));
        GotoActivity.gotoActiviy(getActivity(), BuyActivity.class, bundle);
    }

    private void share() {

    }

    private void addCart(int count, int skuId) {

        if (!UserManager.getInstance().isLogin()) {
            GotoActivity.gotoActiviy(this.getActivity(), LoginActivity.class);
            SharePreferenceUtils.removeString(this.getActivity(), "KEY_TOKEN");
            return;
        }
        JSONObject params = new JSONObject();

        try {
            params.put("count", count);
            params.put("goodsId", manSongGoodsId);
            params.put("skuId", skuId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiOkHttp.addShopCar(this.getActivity(), params, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    int code1 = data.getInt("code");
                    if (code1 == 200) {
                        ToastUtil.show(getActivity(), "添加成功");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });

    }

    private void changeNumber() {

        if (TextUtils.isEmpty(chooseNumberEditText.getText().toString())) {
            Toast.makeText(getActivity(), "数量不能为空！", Toast.LENGTH_LONG).show();
            chooseNumberEditText.setText("1");
            chooseNumberEditText.setSelection(1);
            return;
        }

        int number = Integer.parseInt(chooseNumberEditText.getText().toString());

        if (number <= 0) {
            Toast.makeText(getActivity(), "最低要买 1 件", Toast.LENGTH_LONG).show();
            number = 1;
        }

        if (!TextUtils.isEmpty(upperLimitString)) {
            int upper = Integer.parseInt(upperLimitString);
            if (number > upper) {
                number = upper;
                Toast.makeText(getActivity(), "每人最高限购：" + number + " 件", Toast.LENGTH_LONG).show();
            }
        }

        if (!TextUtils.isEmpty(lowerLimitString)) {
            int lower = Integer.parseInt(lowerLimitString);
            if (number < lower) {
                number = lower;
                Toast.makeText(getActivity(), "最低要购买：" + number + " 件", Toast.LENGTH_LONG).show();
            }
        }

        int storage = goodsStorageString;

        if (number > storage) {
            number = storage;
            Toast.makeText(getActivity(), "库存不足！", Toast.LENGTH_SHORT).show();
        }

        String temp = number + "";
        chooseNumberEditText.setText(temp);
        chooseNumberEditText.setSelection(temp.length());

    }

    private void favoritesAdd() {

        Toast.makeText(getActivity(), "收藏中...", Toast.LENGTH_LONG).show();

    }

    private void favoritesDel() {

        Toast.makeText(getActivity(), "取消收藏中...", Toast.LENGTH_LONG).show();

    }

    private void showPopupwindow() {
        if (mSizeList == null || mSizeList.size() < 1) {
            return;
        }
        sizePopWin = new GoodSizePopupwindow(getActivity(), mSizeList, onClickListener, this, flagShow);
        View contentView = sizePopWin.getContentView();
        addCartNumTv = ((TextView) contentView.findViewById(R.id.goodsRule_numTv));
        //设置Popupwindow显示位置（从底部弹出）
        sizePopWin.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //当弹出Popupwindow时，背景变半透明
        darkenBackgroud(0.4f);
        //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
        sizePopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackgroud(1f);
            }
        });
    }

    private void hidePopupwindow() {
        if (sizePopWin != null) {
            if (sizePopWin.isShowing()) {
                sizePopWin.dismiss();
            }
        }
    }

    private void darkenBackgroud(Float bgcolor) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgcolor;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//让窗口背景后面的任何东西变暗
        getActivity().getWindow().setAttributes(lp);
    }

    /**
     * popupwindow的点击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.goodsRule_minusRelative:
                    int count = Integer.valueOf((String) addCartNumTv.getText());
                    if (count == 1) {
                        ToastUtil.show(getActivity(), "最低购买一件");
                    } else {
                        count--;
                        addCartNumTv.setText((count) + "");
                    }
                    break;
                case R.id.goodsRule_addRelative:
                    int count2 = Integer.valueOf((String) addCartNumTv.getText());
                    count2++;
                    if (count2 > goodsStorageString) {
                        ToastUtil.show(getActivity(), "库存不足");
                    } else {
                        addCartNumTv.setText(count2 + "");
                    }
                    break;
                case R.id.tv_add_car:
                    int skuId = mSizeList.get(currentPosition).getId();
                    int count3 = Integer.valueOf((String) addCartNumTv.getText());
                    addCart(count3, skuId);
                    hidePopupwindow();
                    break;
                case R.id.tv_buy:
                    buy();
                    hidePopupwindow();
                    break;

                case R.id.btn_confirm:
                    if (flagShow == 1) {
                        buy();
                    } else if (flagShow == 2) {
                        int skuId1 = mSizeList.get(currentPosition).getId();
                        int count1 = Integer.valueOf((String) addCartNumTv.getText());
                        addCart(count1, skuId1);
                    } else {
                        return;
                    }
                    hidePopupwindow();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.customerTextView:
                boolean selected = view.isSelected();
                shopCollect(selected,view);
                break;
        }
    }

    public void shopCollect(boolean isSelect, final View view) {
        JSONObject param = new JSONObject();
        try {
            param.put("goodsId", mGoodsId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (isSelect) {
            ApiOkHttp.cancelCollect(getActivity(), param, new OnRequestDataListener() {
                @Override
                public void requestSuccess(int code, JSONObject data) {
                    try {
                        int code1 = data.getInt("code");
                        String msg = data.getString("msg");
                        if (code1 == 200) {
                            view.setSelected(false);
                        }
                        ToastUtil.show(getActivity(),msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void requestFailure(int code, String msg) {

                }
            });
        } else {
            ApiOkHttp.addCollect(getActivity(), param, new OnRequestDataListener() {
                @Override
                public void requestSuccess(int code, JSONObject data) {
                    try {
                        int code1 = data.getInt("code");
                        String msg = data.getString("msg");
                        if (code1 == 200) {
                            view.setSelected(true);
                        }
                        ToastUtil.show(getActivity(),msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void requestFailure(int code, String msg) {

                }
            });
        }


    }
}
